﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SlamCms.Common;
using SlamCms.Configuration;
using SlamCms.Data;
using System.Web;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Threading;
using System.Data.EntityClient;
using System.Web.Security;
using SlamCms.Web;

namespace SlamCms.SharePoint.Core
{
	public static class SlamCmsContext
	{
		private static DataContext _context;

		public static CookieManager Cookies
		{
			get
			{
				return new CookieManager(new HttpContextWrapper(HttpContext.Current), FormsAuthentication.CookieDomain);
			}
		}

		public static DataContext Data
		{
			get
			{

				try
				{
					_context = SlamCmsConfiguration.Instance.DependencyResolver.GetService(typeof(DataContext)) as DataContext;
				}
				catch (NullReferenceException) { }

				if (_context == null)
					_context = new DataContext();

				return _context;
			}
		}
		
		public static SlamCms.SharePoint.Data.Entities Entities
		{
			get
			{
				if (HttpContext.Current.Items["SlamCmsContext.Entities"] == null)
				{

					string connectionString = new DefaultDbConnectionResolver().ConnectionString;
					string modelName = "Data.SlamCms";
					EntityConnectionStringBuilder entityConnection = new EntityConnectionStringBuilder();
					entityConnection.Provider = "System.Data.SqlClient";
					if (!connectionString.Contains("Persist Security Info"))
					{
						connectionString = connectionString.TrimEnd(';') + ";Persist Security Info=True;";
					}
					entityConnection.ProviderConnectionString = connectionString;
					entityConnection.Metadata = String.Format("res://*/{0}.csdl|res://*/{0}.ssdl|res://*/{0}.msl", modelName);
					HttpContext.Current.Items.Add("SlamCmsContext.Entities", new SlamCms.SharePoint.Data.Entities(entityConnection.ToString()));
				}
				return HttpContext.Current.Items["SlamCmsContext.Entities"] as SlamCms.SharePoint.Data.Entities;
			}
		}

		public static SharePointApplication SharePoint
		{
			get
			{	
				return new SharePointApplication();
			}
		}

		public static void GlobalSettings(Action<SPWeb> action, string url)
		{
			string topSiteCollectionUrl = new Uri(url).GetLeftPart(UriPartial.Authority);
			SharePoint.WithElevatedPrivileges().SiteCollection(topSiteCollectionUrl).Site(Constants.SiteNames.GlobalSettings, action);
		}

		public static void GlobalSettings(Action<SPWeb> action)
		{
			string topSiteCollectionUrl = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
			SharePoint.WithElevatedPrivileges().SiteCollection(topSiteCollectionUrl).Site(Constants.SiteNames.GlobalSettings, action);
		}

		public static SharePointSite GlobalSettings()
		{
			string topSiteCollectionUrl = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
			return SharePoint.WithElevatedPrivileges().SiteCollection(topSiteCollectionUrl).Site(Constants.SiteNames.GlobalSettings);
		}

		public static User User
		{
			get
			{
				string currentUserName = HttpContext.Current.User.Identity.Name;
				if (currentUserName.Contains("|"))
					currentUserName = currentUserName.Split('|').Last();

				User currentUser = Data.Users.Where(u => u.UserName.Equals(currentUserName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
				if (currentUser == null)
				{
					SPWeb currentWeb = SPControl.GetContextWeb(HttpContext.Current);
					SPUser currentSpUser = currentWeb.CurrentUser;
					currentUser = new User();
					currentUser.UserName = currentUserName;
					currentUser.Name = currentSpUser.Name;
					currentUser.Email = currentSpUser.Email;
				}

				if(currentUser.Language.IsNullOrEmpty())
					currentUser.Language = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

				return currentUser;
			}
		}
	}
}
